package org.openwork.portlet.skillmanagement.service.persistence;

import com.liferay.portal.NoSuchModelException;
import com.liferay.portal.kernel.annotation.BeanReference;
import com.liferay.portal.kernel.cache.CacheRegistry;
import com.liferay.portal.kernel.dao.orm.EntityCacheUtil;
import com.liferay.portal.kernel.dao.orm.FinderCacheUtil;
import com.liferay.portal.kernel.dao.orm.FinderPath;
import com.liferay.portal.kernel.dao.orm.Query;
import com.liferay.portal.kernel.dao.orm.QueryPos;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.dao.orm.Session;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.InstanceFactory;
import com.liferay.portal.kernel.util.OrderByComparator;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.model.ModelListener;
import com.liferay.portal.service.persistence.BatchSessionUtil;
import com.liferay.portal.service.persistence.GroupPersistence;
import com.liferay.portal.service.persistence.ResourcePersistence;
import com.liferay.portal.service.persistence.UserPersistence;
import com.liferay.portal.service.persistence.impl.BasePersistenceImpl;

import org.openwork.portlet.skillmanagement.NoSuchCategoryException;
import org.openwork.portlet.skillmanagement.model.SkillCategory;
import org.openwork.portlet.skillmanagement.model.impl.SkillCategoryImpl;
import org.openwork.portlet.skillmanagement.model.impl.SkillCategoryModelImpl;
import org.openwork.portlet.skillmanagement.service.persistence.SkillCategoryPersistence;
import org.openwork.portlet.skillmanagement.service.persistence.SkillPersistence;
import org.openwork.portlet.skillmanagement.service.persistence.SkillUserPersistence;

import java.io.Serializable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * <a href="SkillCategoryPersistenceImpl.java.html"><b><i>View Source</i></b></a>
 *
 * <p>
 * ServiceBuilder generated this class. Modifications in this class will be
 * overwritten the next time is generated.
 * </p>
 *
 * @author    Samuel Garcia Martinez
 * @see       SkillCategoryPersistence
 * @see       SkillCategoryUtil
 * @generated
 */
public class SkillCategoryPersistenceImpl extends BasePersistenceImpl<SkillCategory>
    implements SkillCategoryPersistence {
    public static final String FINDER_CLASS_NAME_ENTITY = SkillCategoryImpl.class.getName();
    public static final String FINDER_CLASS_NAME_LIST = FINDER_CLASS_NAME_ENTITY +
        ".List";
    public static final FinderPath FINDER_PATH_FIND_BY_GROUPID = new FinderPath(SkillCategoryModelImpl.ENTITY_CACHE_ENABLED,
            SkillCategoryModelImpl.FINDER_CACHE_ENABLED,
            FINDER_CLASS_NAME_LIST, "findByGroupId",
            new String[] {
                Long.class.getName(),
                
            "java.lang.Integer", "java.lang.Integer",
                "com.liferay.portal.kernel.util.OrderByComparator"
            });
    public static final FinderPath FINDER_PATH_COUNT_BY_GROUPID = new FinderPath(SkillCategoryModelImpl.ENTITY_CACHE_ENABLED,
            SkillCategoryModelImpl.FINDER_CACHE_ENABLED,
            FINDER_CLASS_NAME_LIST, "countByGroupId",
            new String[] { Long.class.getName() });
    public static final FinderPath FINDER_PATH_FIND_ALL = new FinderPath(SkillCategoryModelImpl.ENTITY_CACHE_ENABLED,
            SkillCategoryModelImpl.FINDER_CACHE_ENABLED,
            FINDER_CLASS_NAME_LIST, "findAll", new String[0]);
    public static final FinderPath FINDER_PATH_COUNT_ALL = new FinderPath(SkillCategoryModelImpl.ENTITY_CACHE_ENABLED,
            SkillCategoryModelImpl.FINDER_CACHE_ENABLED,
            FINDER_CLASS_NAME_LIST, "countAll", new String[0]);
    private static final String _SQL_SELECT_SKILLCATEGORY = "SELECT skillCategory FROM SkillCategory skillCategory";
    private static final String _SQL_SELECT_SKILLCATEGORY_WHERE = "SELECT skillCategory FROM SkillCategory skillCategory WHERE ";
    private static final String _SQL_COUNT_SKILLCATEGORY = "SELECT COUNT(*) FROM SkillCategory skillCategory";
    private static final String _SQL_COUNT_SKILLCATEGORY_WHERE = "SELECT COUNT(*) FROM SkillCategory skillCategory WHERE ";
    private static final String _FINDER_COLUMN_GROUPID_GROUPID_2 = "skillCategory.groupId = ?";
    private static final String _ORDER_BY_ENTITY_ALIAS = "skillCategory.";
    private static final String _NO_SUCH_ENTITY_WITH_PRIMARY_KEY = "No SkillCategory exists with the primary key ";
    private static final String _NO_SUCH_ENTITY_WITH_KEY = "No SkillCategory exists with the key {";
    private static Log _log = LogFactoryUtil.getLog(SkillCategoryPersistenceImpl.class);
    @BeanReference(type = SkillCategoryPersistence.class)
    protected SkillCategoryPersistence skillCategoryPersistence;
    @BeanReference(type = SkillPersistence.class)
    protected SkillPersistence skillPersistence;
    @BeanReference(type = SkillUserPersistence.class)
    protected SkillUserPersistence skillUserPersistence;
    @BeanReference(type = GroupPersistence.class)
    protected GroupPersistence groupPersistence;
    @BeanReference(type = ResourcePersistence.class)
    protected ResourcePersistence resourcePersistence;
    @BeanReference(type = UserPersistence.class)
    protected UserPersistence userPersistence;

    public void cacheResult(SkillCategory skillCategory) {
        EntityCacheUtil.putResult(SkillCategoryModelImpl.ENTITY_CACHE_ENABLED,
            SkillCategoryImpl.class, skillCategory.getPrimaryKey(),
            skillCategory);
    }

    public void cacheResult(List<SkillCategory> skillCategories) {
        for (SkillCategory skillCategory : skillCategories) {
            if (EntityCacheUtil.getResult(
                        SkillCategoryModelImpl.ENTITY_CACHE_ENABLED,
                        SkillCategoryImpl.class, skillCategory.getPrimaryKey(),
                        this) == null) {
                cacheResult(skillCategory);
            }
        }
    }

    public void clearCache() {
        CacheRegistry.clear(SkillCategoryImpl.class.getName());
        EntityCacheUtil.clearCache(SkillCategoryImpl.class.getName());
        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_ENTITY);
        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);
    }

    public void clearCache(SkillCategory skillCategory) {
        EntityCacheUtil.removeResult(SkillCategoryModelImpl.ENTITY_CACHE_ENABLED,
            SkillCategoryImpl.class, skillCategory.getPrimaryKey());
    }

    public SkillCategory create(long id) {
        SkillCategory skillCategory = new SkillCategoryImpl();

        skillCategory.setNew(true);
        skillCategory.setPrimaryKey(id);

        return skillCategory;
    }

    public SkillCategory remove(Serializable primaryKey)
        throws NoSuchModelException, SystemException {
        return remove(((Long) primaryKey).longValue());
    }

    public SkillCategory remove(long id)
        throws NoSuchCategoryException, SystemException {
        Session session = null;

        try {
            session = openSession();

            SkillCategory skillCategory = (SkillCategory) session.get(SkillCategoryImpl.class,
                    new Long(id));

            if (skillCategory == null) {
                if (_log.isWarnEnabled()) {
                    _log.warn(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + id);
                }

                throw new NoSuchCategoryException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
                    id);
            }

            return remove(skillCategory);
        } catch (NoSuchCategoryException nsee) {
            throw nsee;
        } catch (Exception e) {
            throw processException(e);
        } finally {
            closeSession(session);
        }
    }

    public SkillCategory remove(SkillCategory skillCategory)
        throws SystemException {
        for (ModelListener<SkillCategory> listener : listeners) {
            listener.onBeforeRemove(skillCategory);
        }

        skillCategory = removeImpl(skillCategory);

        for (ModelListener<SkillCategory> listener : listeners) {
            listener.onAfterRemove(skillCategory);
        }

        return skillCategory;
    }

    protected SkillCategory removeImpl(SkillCategory skillCategory)
        throws SystemException {
        skillCategory = toUnwrappedModel(skillCategory);

        Session session = null;

        try {
            session = openSession();

            if (skillCategory.isCachedModel() || BatchSessionUtil.isEnabled()) {
                Object staleObject = session.get(SkillCategoryImpl.class,
                        skillCategory.getPrimaryKeyObj());

                if (staleObject != null) {
                    session.evict(staleObject);
                }
            }

            session.delete(skillCategory);

            session.flush();
        } catch (Exception e) {
            throw processException(e);
        } finally {
            closeSession(session);
        }

        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);

        EntityCacheUtil.removeResult(SkillCategoryModelImpl.ENTITY_CACHE_ENABLED,
            SkillCategoryImpl.class, skillCategory.getPrimaryKey());

        return skillCategory;
    }

    public SkillCategory updateImpl(
        org.openwork.portlet.skillmanagement.model.SkillCategory skillCategory,
        boolean merge) throws SystemException {
        skillCategory = toUnwrappedModel(skillCategory);

        Session session = null;

        try {
            session = openSession();

            BatchSessionUtil.update(session, skillCategory, merge);

            skillCategory.setNew(false);
        } catch (Exception e) {
            throw processException(e);
        } finally {
            closeSession(session);
        }

        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);

        EntityCacheUtil.putResult(SkillCategoryModelImpl.ENTITY_CACHE_ENABLED,
            SkillCategoryImpl.class, skillCategory.getPrimaryKey(),
            skillCategory);

        return skillCategory;
    }

    protected SkillCategory toUnwrappedModel(SkillCategory skillCategory) {
        if (skillCategory instanceof SkillCategoryImpl) {
            return skillCategory;
        }

        SkillCategoryImpl skillCategoryImpl = new SkillCategoryImpl();

        skillCategoryImpl.setNew(skillCategory.isNew());
        skillCategoryImpl.setPrimaryKey(skillCategory.getPrimaryKey());

        skillCategoryImpl.setId(skillCategory.getId());
        skillCategoryImpl.setGroupId(skillCategory.getGroupId());
        skillCategoryImpl.setUserId(skillCategory.getUserId());
        skillCategoryImpl.setCreateDate(skillCategory.getCreateDate());
        skillCategoryImpl.setModifiedDate(skillCategory.getModifiedDate());
        skillCategoryImpl.setName(skillCategory.getName());

        return skillCategoryImpl;
    }

    public SkillCategory findByPrimaryKey(Serializable primaryKey)
        throws NoSuchModelException, SystemException {
        return findByPrimaryKey(((Long) primaryKey).longValue());
    }

    public SkillCategory findByPrimaryKey(long id)
        throws NoSuchCategoryException, SystemException {
        SkillCategory skillCategory = fetchByPrimaryKey(id);

        if (skillCategory == null) {
            if (_log.isWarnEnabled()) {
                _log.warn(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + id);
            }

            throw new NoSuchCategoryException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
                id);
        }

        return skillCategory;
    }

    public SkillCategory fetchByPrimaryKey(Serializable primaryKey)
        throws SystemException {
        return fetchByPrimaryKey(((Long) primaryKey).longValue());
    }

    public SkillCategory fetchByPrimaryKey(long id) throws SystemException {
        SkillCategory skillCategory = (SkillCategory) EntityCacheUtil.getResult(SkillCategoryModelImpl.ENTITY_CACHE_ENABLED,
                SkillCategoryImpl.class, id, this);

        if (skillCategory == null) {
            Session session = null;

            try {
                session = openSession();

                skillCategory = (SkillCategory) session.get(SkillCategoryImpl.class,
                        new Long(id));
            } catch (Exception e) {
                throw processException(e);
            } finally {
                if (skillCategory != null) {
                    cacheResult(skillCategory);
                }

                closeSession(session);
            }
        }

        return skillCategory;
    }

    public List<SkillCategory> findByGroupId(long groupId)
        throws SystemException {
        return findByGroupId(groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
    }

    public List<SkillCategory> findByGroupId(long groupId, int start, int end)
        throws SystemException {
        return findByGroupId(groupId, start, end, null);
    }

    public List<SkillCategory> findByGroupId(long groupId, int start, int end,
        OrderByComparator orderByComparator) throws SystemException {
        Object[] finderArgs = new Object[] {
                new Long(groupId),
                
                String.valueOf(start), String.valueOf(end),
                String.valueOf(orderByComparator)
            };

        List<SkillCategory> list = (List<SkillCategory>) FinderCacheUtil.getResult(FINDER_PATH_FIND_BY_GROUPID,
                finderArgs, this);

        if (list == null) {
            Session session = null;

            try {
                session = openSession();

                StringBundler query = null;

                if (orderByComparator != null) {
                    query = new StringBundler(3 +
                            (orderByComparator.getOrderByFields().length * 3));
                } else {
                    query = new StringBundler(3);
                }

                query.append(_SQL_SELECT_SKILLCATEGORY_WHERE);

                query.append(_FINDER_COLUMN_GROUPID_GROUPID_2);

                if (orderByComparator != null) {
                    appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
                        orderByComparator);
                }
                else {
                    query.append(SkillCategoryModelImpl.ORDER_BY_JPQL);
                }

                String sql = query.toString();

                Query q = session.createQuery(sql);

                QueryPos qPos = QueryPos.getInstance(q);

                qPos.add(groupId);

                list = (List<SkillCategory>) QueryUtil.list(q, getDialect(),
                        start, end);
            } catch (Exception e) {
                throw processException(e);
            } finally {
                if (list == null) {
                    list = new ArrayList<SkillCategory>();
                }

                cacheResult(list);

                FinderCacheUtil.putResult(FINDER_PATH_FIND_BY_GROUPID,
                    finderArgs, list);

                closeSession(session);
            }
        }

        return list;
    }

    public SkillCategory findByGroupId_First(long groupId,
        OrderByComparator orderByComparator)
        throws NoSuchCategoryException, SystemException {
        List<SkillCategory> list = findByGroupId(groupId, 0, 1,
                orderByComparator);

        if (list.isEmpty()) {
            StringBundler msg = new StringBundler(4);

            msg.append(_NO_SUCH_ENTITY_WITH_KEY);

            msg.append("groupId=");
            msg.append(groupId);

            msg.append(StringPool.CLOSE_CURLY_BRACE);

            throw new NoSuchCategoryException(msg.toString());
        } else {
            return list.get(0);
        }
    }

    public SkillCategory findByGroupId_Last(long groupId,
        OrderByComparator orderByComparator)
        throws NoSuchCategoryException, SystemException {
        int count = countByGroupId(groupId);

        List<SkillCategory> list = findByGroupId(groupId, count - 1, count,
                orderByComparator);

        if (list.isEmpty()) {
            StringBundler msg = new StringBundler(4);

            msg.append(_NO_SUCH_ENTITY_WITH_KEY);

            msg.append("groupId=");
            msg.append(groupId);

            msg.append(StringPool.CLOSE_CURLY_BRACE);

            throw new NoSuchCategoryException(msg.toString());
        } else {
            return list.get(0);
        }
    }

    public SkillCategory[] findByGroupId_PrevAndNext(long id, long groupId,
        OrderByComparator orderByComparator)
        throws NoSuchCategoryException, SystemException {
        SkillCategory skillCategory = findByPrimaryKey(id);

        Session session = null;

        try {
            session = openSession();

            SkillCategory[] array = new SkillCategoryImpl[3];

            array[0] = getByGroupId_PrevAndNext(session, skillCategory,
                    groupId, orderByComparator, true);

            array[1] = skillCategory;

            array[2] = getByGroupId_PrevAndNext(session, skillCategory,
                    groupId, orderByComparator, false);

            return array;
        } catch (Exception e) {
            throw processException(e);
        } finally {
            closeSession(session);
        }
    }

    protected SkillCategory getByGroupId_PrevAndNext(Session session,
        SkillCategory skillCategory, long groupId,
        OrderByComparator orderByComparator, boolean previous) {
        StringBundler query = null;

        if (orderByComparator != null) {
            query = new StringBundler(6 +
                    (orderByComparator.getOrderByFields().length * 6));
        } else {
            query = new StringBundler(3);
        }

        query.append(_SQL_SELECT_SKILLCATEGORY_WHERE);

        query.append(_FINDER_COLUMN_GROUPID_GROUPID_2);

        if (orderByComparator != null) {
            String[] orderByFields = orderByComparator.getOrderByFields();

            if (orderByFields.length > 0) {
                query.append(WHERE_AND);
            }

            for (int i = 0; i < orderByFields.length; i++) {
                query.append(_ORDER_BY_ENTITY_ALIAS);
                query.append(orderByFields[i]);

                if ((i + 1) < orderByFields.length) {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(WHERE_GREATER_THAN_HAS_NEXT);
                    } else {
                        query.append(WHERE_LESSER_THAN_HAS_NEXT);
                    }
                } else {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(WHERE_GREATER_THAN);
                    } else {
                        query.append(WHERE_LESSER_THAN);
                    }
                }
            }

            query.append(ORDER_BY_CLAUSE);

            for (int i = 0; i < orderByFields.length; i++) {
                query.append(_ORDER_BY_ENTITY_ALIAS);
                query.append(orderByFields[i]);

                if ((i + 1) < orderByFields.length) {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(ORDER_BY_ASC_HAS_NEXT);
                    } else {
                        query.append(ORDER_BY_DESC_HAS_NEXT);
                    }
                } else {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(ORDER_BY_ASC);
                    } else {
                        query.append(ORDER_BY_DESC);
                    }
                }
            }
        }
        else {
            query.append(SkillCategoryModelImpl.ORDER_BY_JPQL);
        }

        String sql = query.toString();

        Query q = session.createQuery(sql);

        q.setFirstResult(0);
        q.setMaxResults(2);

        QueryPos qPos = QueryPos.getInstance(q);

        qPos.add(groupId);

        if (orderByComparator != null) {
            Object[] values = orderByComparator.getOrderByValues(skillCategory);

            for (Object value : values) {
                qPos.add(value);
            }
        }

        List<SkillCategory> list = q.list();

        if (list.size() == 2) {
            return list.get(1);
        } else {
            return null;
        }
    }

    public List<SkillCategory> findAll() throws SystemException {
        return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
    }

    public List<SkillCategory> findAll(int start, int end)
        throws SystemException {
        return findAll(start, end, null);
    }

    public List<SkillCategory> findAll(int start, int end,
        OrderByComparator orderByComparator) throws SystemException {
        Object[] finderArgs = new Object[] {
                String.valueOf(start), String.valueOf(end),
                String.valueOf(orderByComparator)
            };

        List<SkillCategory> list = (List<SkillCategory>) FinderCacheUtil.getResult(FINDER_PATH_FIND_ALL,
                finderArgs, this);

        if (list == null) {
            Session session = null;

            try {
                session = openSession();

                StringBundler query = null;
                String sql = null;

                if (orderByComparator != null) {
                    query = new StringBundler(2 +
                            (orderByComparator.getOrderByFields().length * 3));

                    query.append(_SQL_SELECT_SKILLCATEGORY);

                    appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
                        orderByComparator);

                    sql = query.toString();
                }
                else {
                    sql = _SQL_SELECT_SKILLCATEGORY.concat(SkillCategoryModelImpl.ORDER_BY_JPQL);
                }

                Query q = session.createQuery(sql);

                if (orderByComparator == null) {
                    list = (List<SkillCategory>) QueryUtil.list(q,
                            getDialect(), start, end, false);

                    Collections.sort(list);
                } else {
                    list = (List<SkillCategory>) QueryUtil.list(q,
                            getDialect(), start, end);
                }
            } catch (Exception e) {
                throw processException(e);
            } finally {
                if (list == null) {
                    list = new ArrayList<SkillCategory>();
                }

                cacheResult(list);

                FinderCacheUtil.putResult(FINDER_PATH_FIND_ALL, finderArgs, list);

                closeSession(session);
            }
        }

        return list;
    }

    public void removeByGroupId(long groupId) throws SystemException {
        for (SkillCategory skillCategory : findByGroupId(groupId)) {
            remove(skillCategory);
        }
    }

    public void removeAll() throws SystemException {
        for (SkillCategory skillCategory : findAll()) {
            remove(skillCategory);
        }
    }

    public int countByGroupId(long groupId) throws SystemException {
        Object[] finderArgs = new Object[] { new Long(groupId) };

        Long count = (Long) FinderCacheUtil.getResult(FINDER_PATH_COUNT_BY_GROUPID,
                finderArgs, this);

        if (count == null) {
            Session session = null;

            try {
                session = openSession();

                StringBundler query = new StringBundler(2);

                query.append(_SQL_COUNT_SKILLCATEGORY_WHERE);

                query.append(_FINDER_COLUMN_GROUPID_GROUPID_2);

                String sql = query.toString();

                Query q = session.createQuery(sql);

                QueryPos qPos = QueryPos.getInstance(q);

                qPos.add(groupId);

                count = (Long) q.uniqueResult();
            } catch (Exception e) {
                throw processException(e);
            } finally {
                if (count == null) {
                    count = Long.valueOf(0);
                }

                FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_GROUPID,
                    finderArgs, count);

                closeSession(session);
            }
        }

        return count.intValue();
    }

    public int countAll() throws SystemException {
        Object[] finderArgs = new Object[0];

        Long count = (Long) FinderCacheUtil.getResult(FINDER_PATH_COUNT_ALL,
                finderArgs, this);

        if (count == null) {
            Session session = null;

            try {
                session = openSession();

                Query q = session.createQuery(_SQL_COUNT_SKILLCATEGORY);

                count = (Long) q.uniqueResult();
            } catch (Exception e) {
                throw processException(e);
            } finally {
                if (count == null) {
                    count = Long.valueOf(0);
                }

                FinderCacheUtil.putResult(FINDER_PATH_COUNT_ALL, finderArgs,
                    count);

                closeSession(session);
            }
        }

        return count.intValue();
    }

    public void afterPropertiesSet() {
        String[] listenerClassNames = StringUtil.split(GetterUtil.getString(
                    com.liferay.util.service.ServiceProps.get(
                        "value.object.listener.org.openwork.portlet.skillmanagement.model.SkillCategory")));

        if (listenerClassNames.length > 0) {
            try {
                List<ModelListener<SkillCategory>> listenersList = new ArrayList<ModelListener<SkillCategory>>();

                for (String listenerClassName : listenerClassNames) {
                    listenersList.add((ModelListener<SkillCategory>) InstanceFactory.newInstance(
                            listenerClassName));
                }

                listeners = listenersList.toArray(new ModelListener[listenersList.size()]);
            } catch (Exception e) {
                _log.error(e);
            }
        }
    }
}
